package com.example.demo.util;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;

import java.io.ByteArrayOutputStream;
import java.io.File;

public class PdfUtils {
	
	public static ByteArrayOutputStream watermarkPDF(File fileStored, String str) throws Exception {
        PDDocument doc;
        doc = PDDocument.load(fileStored);
        doc.setAllSecurityToBeRemoved(true);
        for(PDPage page:doc.getPages()){
            PDPageContentStream cs = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true, true);
            PDFont font = PDType1Font.HELVETICA;
            float fontSize = 22.0f;
            PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
           
            r0.setNonStrokingAlphaConstant(0.2f); // 透明度
            r0.setAlphaSourceFlag(true);
            cs.setGraphicsStateParameters(r0);
            cs.setNonStrokingColor(102, 102, 102);//字体 
            cs.beginText();
            cs.setFont(font, fontSize);
            float h = page.getMediaBox().getHeight();
            float w = page.getMediaBox().getWidth();
            
            int rows=(int) ((h-50)/150);
            int cols=(int) ((w-20)/150+1);
            for (int i = 0; i < rows; i++) {  
              for (int j = 0; j < cols; j++) {  
            	  cs.setTextMatrix(Matrix.getRotateInstance(45,j*150+ 30f,i*150+70f)); 
            	  cs.showText(str);
              }
            }
            cs.endText();
            cs.close();
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        doc.save(output);
        doc.getDocument().close();
        doc.close();
        return output;
    }
}
